import java.util.*;

public class Solution692 {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> map=new HashMap<>();
        for (String word : words) {
            map.put(word,map.getOrDefault(word,0)+1);
        }
        List<Map.Entry<String,Integer>> list=new ArrayList<>(map.entrySet());
        Collections.sort(list,(a,b)->{
            if (a.getValue()!=b.getValue()){
                return b.getValue()-a.getValue();
            }else{
                return a.getKey().compareTo(b.getKey());
            }
        });
        List<String> ans=new ArrayList<>();
        for (int i=0;i<k;i++){
            ans.add(list.get(i).getKey());
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution692().topKFrequent(new String[]{"i", "love", "leetcode", "i", "love", "coding"},2));
    }
}
